package com.jessechanrui.template.shardingsphere.controller;

import com.jessechanrui.template.shardingsphere.entity.Employee;
import com.jessechanrui.template.shardingsphere.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/api/v1/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping
    @ResponseBody
    public ResponseEntity<List<Employee>> findEmployee(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size) {
        return ResponseEntity.ok(employeeService.findPage(page, size).stream().collect(Collectors.toList()));
    }

    @PostMapping
    @ResponseBody
    public ResponseEntity<List<Employee>> saveEmployee(@RequestBody List<Employee> employees) {
        return ResponseEntity.ok(employeeService.saveAll(employees));
    }

    @PostMapping("/exp/trans")
    @ResponseBody
    public ResponseEntity<Void> saveEmployeeTransTest(@RequestBody List<Employee> employees) {
        employeeService.saveOneByOneWithTrans(employees);
        return ResponseEntity.ok().build();
    }
    @PostMapping("/exp/notrans")
    @ResponseBody
    public ResponseEntity<Void> saveEmployeeWithExp(@RequestBody List<Employee> employees) {
        employeeService.saveOneByOneWithoutTrans(employees);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{employeeId}")
    @ResponseBody
    public ResponseEntity<Employee> findEmployee(@PathVariable("employeeId") Long employeeId) {
        return ResponseEntity.ok(employeeService.find(employeeId));
    }

}
